﻿using System.IO;
using System.Text;

namespace Game.Foundation
{
    public class BytesParser
    {
        private MemoryStream _baseStream;
        private BinaryReader _reader;

        public BytesParser(byte[] data)
        {
            this._baseStream = new MemoryStream(data, false);
            this._reader = new BinaryReader(this._baseStream);
        }

        public byte GetByte()
        {
            return this._reader.ReadByte();
        }

        public short GetShort()
        {
            return this._reader.ReadInt16();
        }

        public int GetInt()
        {
            return this._reader.ReadInt32();
        }

        public string GetString()
        {
            return this._reader.ReadString();
        }

        public byte[] GetRangeArray(int length)
        {
            return this._reader.ReadBytes(length);
        }

        /// <summary>
        /// 字符串长度为ushort
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] StringToBytes(string str)
        {
            byte[] data;
            using (MemoryStream baseStream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(baseStream, Encoding.UTF8))
                {
                    writer.Write(str);
                    data = baseStream.ToArray();
                }
            }

            return data;
        }
    }
}
